package org.eenie.kdassistant.ui.login.xz;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.eenie.kdassistant.R;
import org.eenie.kdassistant.net.ParamsAnalog;
import org.eenie.kdassistant.net.zzt_api.ZZTApi;
import org.eenie.kdassistant.ui.BaseActivity;
import org.eenie.kdassistant.utils.LogUtil;
import org.eenie.kdassistant.utils.ToastUtils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.UUID;

import okhttp3.ResponseBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ZZTLoginWebActivity extends BaseActivity {
    WebView mWebView;
    private String url_login = "https://connect.zto.com/oauth2/authorize?appid=ztDNprSNTtWdaQeoAcHgtKNQ&redirect_uri=zzt%3A%2F%2Foauth2&response_type=token&scope=userinfo,usercert,usercontact,user_id,node_id&state=" + UUID.randomUUID();
    ParamsAnalog mParamsAnalog;
    ZZTApi mZZTApi;
    @Override
    public int initContentView() {
        return R.layout.activity_zztlogin_web;
    }

    @Override
    public void initInjector() {
        mParamsAnalog = getApplicationComponent().getParamsAnalog();
        mZZTApi = getApplicationComponent().getZZTApi();
    }

    @Override
    public void initUiAndListener() {
        mWebView = (WebView) findViewById(R.id.web_login);
        mWebView.loadUrl(url_login);
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);

        CookieSyncManager.createInstance(mContext);
        CookieManager var10 = CookieManager.getInstance();
        var10.setAcceptCookie(true);
        var10.removeSessionCookie();


        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        String uuid;
        uuid = getWifiMac(wifiManager);
        mParamsAnalog.setZzt_uuid(uuid);

        var10.setCookie(url_login, "Device-Id=" + uuid);
        var10.setCookie(url_login, "Device-Location=" + mParamsAnalog.getDevice_lat() + "," + mParamsAnalog.getDevice_lng());
        var10.setCookie(url_login, "Device-Wifi-Ssid=" + wifiInfo.getSSID());
        var10.setCookie(url_login, "Device-Wifi-Bssid=" + wifiInfo.getBSSID());
        var10.setCookie(url_login, "Device-Private-Ip-Addr=" + getWifiIp(wifiManager));
        var10.setCookie(url_login, "Device-Name=" + mParamsAnalog.getPhoneBrand());
        var10.setCookie(url_login, "Device-Model=" + mParamsAnalog.getPhoneModel());

        var10.setCookie(url_login, "Platform-Name=android");
        var10.setCookie(url_login, "Platform-Version=" + Build.VERSION.SDK_INT);
        var10.setCookie(url_login, "App-Version=" + "4.1.1");
        var10.setCookie(url_login, "App-Bundle-Id=com.geenk.zto.sys");
        CookieSyncManager.getInstance().sync();

        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (!TextUtils.isEmpty(url) && url.startsWith("zzt://oauth2?")) {
                    LogUtil.e("url = " + url);

                    Uri paramUri = Uri.parse(url);
                    String openId = paramUri.getQueryParameter("openid");
                    String token = paramUri.getQueryParameter("access_token");
                    String refresh_token = paramUri.getQueryParameter("refresh_token");


                    mParamsAnalog.setZzt_opendid(openId);

                    mParamsAnalog.setZzt_token(token);

                    login();


                    return true;
                }

                return super.shouldOverrideUrlLoading(view, url);
            }
        });


    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    private void login() {
        mZZTApi.login()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            JSONObject resObj = JSON.parseObject(responseBody.string());
                            if (resObj.getBoolean("status")) {
                                JSONObject dataObj = resObj.getJSONObject("result");
                                String empCode = dataObj.getString("empCode");
                                mParamsAnalog.setZzt_empCode(empCode);
                                finish();

                            } else {
                                ToastUtils.showShort("登录失败");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public static String getWifiIp(WifiManager var4) {


        String var5;
        if(var4.isWifiEnabled()) {
            var5 = a(var4.getConnectionInfo().getIpAddress());
        } else {
            try {
                Enumeration var1 = NetworkInterface.getNetworkInterfaces();

                while(var1.hasMoreElements()) {
                    Enumeration var2 = ((NetworkInterface)var1.nextElement()).getInetAddresses();

                    while(var2.hasMoreElements()) {
                        InetAddress var6 = (InetAddress)var2.nextElement();
                        if(!var6.isLoopbackAddress()) {
                            var5 = var6.getHostAddress().toString();
                            return var5;
                        }
                    }
                }
            } catch (SocketException e) {
               e.printStackTrace();
            }

            var5 = "";
        }

        return var5;
    }

    private static String a(int var0) {
        return (var0 & 255) + "." + (var0 >> 8 & 255) + "." + (var0 >> 16 & 255) + "." + (var0 >> 24 & 255);
    }

    @SuppressLint("WifiManagerPotentialLeak")
    private String getWifiMac(WifiManager wifiManager ) {
        String mac = wifiManager.getConnectionInfo().getMacAddress();
        return TextUtils.isEmpty(mac) ? "02:00:00:00:00:00" : mac;
    }
}
